<template>
  <div class="chat">
    <div class="login" v-if="currentStatus === 'login'">
      <el-image class="avatar" :src="avatar1" style="width: 70px; height: 70px; border-radius: 50%; display: block;" />
      <Form :formConfig="loginFormConfig" />
    </div>
    <div class="register" v-else-if="currentStatus === 'register'">
      <Form :formConfig="registerFormConfig" />
    </div>
    <div class="main" v-else>
      <el-container>
        <el-aside width="250px" height="100%" class="aside">
          <div class="header">
            <el-image class="avatar" :src="userInfo.avatar" style="width: 40px; height: 40px; border-radius: 50%; display: block;" />
            <el-input
              class="search-input"
              v-model="search"
              placeholder="搜索添加"
              :suffix-icon="Search"
            />
          </div>
          <div class="friend-list">
            <div class="friend-item"
              v-for="conversation in userInfo.conversations"
              :key="conversation.username"
              @click="toggleConversation(conversation.username)"
            >
              <el-image class="avatar" :src="conversation.avatar" style="width: 40px; height: 40px; border-radius: 5px; display: block;" />
              <div class="info">
                <div class="nickname">{{conversation.username}}</div>
                <div class="msg">{{conversation.lastMsg}}</div>
              </div>
              <div class="time">{{conversation.time}}</div>
            </div>
          </div>
        </el-aside>
        <el-container class="content">
          <el-header class="header">
            {{currentConversion.username}}
          </el-header>
          <el-main class="main">
            <el-scrollbar ref="scrollRef" style="padding-right: 12px">
              <div class="msg-wrap" v-for="msg in msgList" :key="msg.time">
                <div class="time"><span>{{ msg.time }}</span></div>
                <!-- 我放消息 -->
                <div class="msg-content-r" v-if="msg.fromUser === userInfo.username">
                  <div class="msg" v-html="msg.msg"></div>
                  <div class="avatar">
                    <el-image class="avatar" :src="userInfo.avatar" style="width: 30px; height: 30px; border-radius: 5px; display: block;" />
                  </div>
                </div>
                <!-- 对方消息 -->
                <div class="msg-content-l" v-else>
                  <div class="avatar">
                    <el-image class="avatar" :src="currentConversion.avatar" style="width: 30px; height: 30px; border-radius: 5px; display: block;" />
                  </div>
                  <div class="msg" v-html="msg.msg"></div>
                </div>
              </div>
            </el-scrollbar>
          </el-main>
          <el-footer height="150px" class="footer">
            <div class="icon-list">
              <el-image :src="bq" style="width: 18px; height: 18px; margin: 8px 10px 8px 0;" />
              <el-image :src="wj" style="width: 18px; height: 18px; margin: 8px 10px 8px 0;" />
              <el-image :src="jq" style="width: 18px; height: 18px; margin: 8px 10px 8px 0;" />
              <el-image :src="lt" style="width: 18px; height: 18px; margin: 8px 10px 8px 0;" />
            </div>
            <el-input
              v-model="msg"
              style="width: 100%;"
              type="textarea"
              class="msg-input"
              @keyup.enter.native="sendMsg"
            />
            <div class="send">
              <el-tooltip :visible="tipVisible" effect="light" placement="top">
                <template #content>
                  <span>发送内容不能为空白</span>
                </template>
                <el-button @click="sendMsg" type="success" plain>
                  发送(S)
                </el-button>
              </el-tooltip>
            </div>
          </el-footer>
        </el-container>
      </el-container>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, inject, nextTick } from 'vue'
import type { Ref } from 'vue'
import Form from '@/components/form'
import { Search } from '@element-plus/icons-vue'
import type { ScrollbarInstance } from 'element-plus'

import avatar1 from '@/assets/img/win-content/avatar1.jpeg'
import bq from '@/assets/img/win-content/chat/1biaoqing.png'
import wj from '@/assets/img/win-content/chat/2folderOpen.png'
import jq from '@/assets/img/win-content/chat/3tupianjianqie.png'
import lt from '@/assets/img/win-content/chat/4chat.png'

import type { Socket } from 'socket.io-client'
import type { DefaultEventsMap } from '@socket.io/component-emitter'

import { loginFormConfig, registerFormConfig } from './config'
import { useAction, elMessage } from '@/utils/send-msg-key'
import { useChatStore } from '@/store/chat'
import { setCache } from '@/utils/local-cache'

const chatStore = useChatStore()

const userInfo: Ref<any> = ref({})
// 登录
const currentStatus = ref('login')
// 事件逻辑处理
const onMsgAction: any = {
  chatLogin: async (data: any) => {
    console.log(data)
    const result = await chatStore.chatLoginAction(data)
    console.log(result)
    if (result.flag) {
      // 登录成功后
      currentStatus.value = 'online'
      setCache('token', result.token)
      setCache('userInfo', result.data)
      userInfo.value = result.data
      // 加入socket
      socket.emit('join', userInfo.value.username)
      elMessage('success', result.msg)
    } else {
      elMessage('warning', result.msg)
    }
  },
  goRegister: () => {
    currentStatus.value = 'register'
  },
  chatRegister: async (data: any) => {
    console.log(data)
    const result = await chatStore.chatRegisterAction(data)
    if (result.flag) {
      elMessage('success', result.msg)
      currentStatus.value = 'login'
    } else {
      elMessage('warning', result.msg)
    }
  },
  goLogin: () => {
    currentStatus.value = 'login'
  }
}
// 注册Form表单的事件
new useAction(onMsgAction)

const search = ref('')
const currentConversion: Ref<any> = ref({})

const toggleConversation = (username: string) => {
  currentConversion.value = userInfo.value.conversations.find((conversation: any) => conversation.username === username)
}
// 消息通信
const socket: Socket<DefaultEventsMap, DefaultEventsMap> = inject('socket')!
const scrollRef = ref<ScrollbarInstance>()

// 消息列表
const msgList: any = reactive([])
// 组件创建：即用户登录后开始接收消息
socket.on('msg', (msgInfo: any) => {
  msgList.push(msgInfo)
})

const tipVisible = ref(false)
const msg = ref('')
const sendMsg = () => {
  if (msg.value.trim().length) {
    const msgInfo = {
      msg: msg.value,
      time: new Date(),
      fromUser: userInfo.value.username,
      toUser: currentConversion.value.username
    }
    socket.emit('msg', msgInfo)
    msgList.push(msgInfo)
    nextTick(() => {
      scrollRef.value!.wrap$!.scrollTop = scrollRef.value!.wrap$!.scrollHeight
    })
    msg.value = ''
  } else {
    tipVisible.value = true
    setTimeout(() => {
      tipVisible.value = false
    }, 1500)
  }
}
</script>

<style lang="less" scoped>
.chat {
  height: 100%;
}
.login, .register {
  width: 300px;
  min-height: 200px;
  margin: 0 auto;
  position: relative;
  top: 120px;
  .avatar {
    margin: 10px auto;
  }
}


.main {
  height: 100%;
  .el-container {
    height: 100%;
  }
  .header {
    display: flex;
    padding: 10px;
    background: rgba(255, 255, 255, .8);
    .search-input {
      margin: 5px 0 0 9px;
      width: 160px;
      height: 30px;
    }
    &:hover {
    background: rgba(255, 255, 255, .9);
    }
  }

  .aside {
    background: rgba(255, 255, 255, .6);
    .friend-list {
      .friend-item {
        cursor: pointer;
        height: 60px;
        display: flex;
        box-sizing: border-box;
        background: rgba(255, 255, 255, .6);
        padding: 10px;
        .info {
          flex: 1;
          margin-left: 10px;
          font-size: 14px;
          width: 125px;
          .nickname {
            height: 22px;
            line-height: 22px;
          }
          .msg {
            width: 100%;
            font-size: 12px;
            color: grey;
            height: 18px;
            line-height: 18px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        .time {
          margin-right: 5px;
          font-size: 12px;
          width: 50px;
          color: grey;
        }
        &:hover {
          background-color: rgba(255, 255, 255, .5);
        }
      }
    }
  }

  .content {
    .header {
      font-size: 18px;
      padding:20px;
      background: rgba(255, 255, 255, .6);
    }
    .main {
      border-bottom: 1px solid #ddd;
      border-top: 1px solid #ddd;
      padding: 5px 10px;
    }
    .msg-wrap {
      width: 100%;
      margin: 10px 0;
      .time {
        width: 100%;
        text-align: center;
        font-size: 14px;
        color: #888;
        line-height: 22px;
      }
      .msg-content-l {
        display: flex;
        .msg {
          background: #a7caee;
          color: #333;
          border-bottom-left-radius: 6px;
          line-height: 24px;
          margin-left: 10px;
          max-width: 60%;
          border-top-right-radius: 6px;
          border-bottom-right-radius: 6px;
          font-size: 15px;
          padding: 3px 10px;
        }
      }
      .msg-content-r {
        display: flex;
        justify-content: flex-end;
        .msg {
          background: #a7caee;
          color: #333;
          border-bottom-left-radius: 6px;
          line-height: 24px;
          margin-right: 10px;
          max-width: 60%;
          border-top-left-radius: 6px;
          border-bottom-right-radius: 6px;
          font-size: 15px;
          padding: 3px 10px;
        }
      }
    }

    .footer {
      .msg-input {
        height: 70px;
        :deep(.el-textarea__inner) {
          height: 64px;
          background-color: rgba(188, 211, 221, .8);
          resize: none;
          box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
          cursor: default;
        }
        :deep(.el-textarea__inner:focus) {
          box-shadow: none;
        }
        :deep(.el-textarea__inner:hover) {
          box-shadow: none;
        }
        :deep(.el-textarea__inner::-webkit-scrollbar) {
          width: 3px;
          background: rgb(182, 214, 226);
        }
        :deep(.el-textarea__inner::-webkit-scrollbar-thumb) {
          box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
          background-color: skyblue;
        }
      }
      .send {
        text-align: right;
      }
    }
  }
}

:deep(.el-input__wrapper) {
  background: rgba(#fff, 0.4);
  position: relative;
  left: 1px;
}
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #fff inset;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #eee inset;
}
:deep(.el-input__inner) {
  color: #333;
}
</style>
